using System.IO;

namespace ColladaDotNet.Pipeline.BSP.Quake3
{
	public class BSPReader
	{
		public ITransformation Transformation = NoTransformation.Value;

		public IBSPFile Parse(Stream s)
		{
			var p = s.Position;
			var Magic = "";
			Magic += (char)s.ReadByte();
			Magic += (char)s.ReadByte();
			Magic += (char)s.ReadByte();
			Magic += (char)s.ReadByte();
			uint version = (uint)s.ReadByte();
			version = (((uint)s.ReadByte())<<8) + version;
			version = (((uint)s.ReadByte()) << 16) + version;
			version = (((uint)s.ReadByte()) << 24) + version;
			s.Position = p;
			switch (Magic)
			{
				case "IBSP":
					switch (version)
					{
						case 0x1C:
							var quake1BSPReader = new Quake1BSPReader();
							quake1BSPReader.Transformation = this.Transformation;
							return quake1BSPReader.Parse(s);
						case 38:
							return Quake2BSPReader.Parse(s);
						case 0x2e: //Quake3
						case 0x2f: //QuakeLive
							var quake3BSPReader = new Quake3BSPReader();
							quake3BSPReader.Transformation = this.Transformation;
							return quake3BSPReader.Parse(s);
						default:
							throw new BSPFormatException("unknown magic " + Magic);
					}
				case "VBSP":
					return SourceEngineBSPReader.Parse(s);
				default:
					throw new BSPFormatException("unknown magic "+Magic);
			}
		}
	}
}